package com.example.demo.controller;

import com.example.demo.common.*;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-09-02
 * Time: 23:37
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/picture")
    public CommonResult picture(@RequestPart("myfile")MultipartFile file) throws IOException {
        if(file == null) {
            return CommonResult.fail(-1, "上传文件失败");
        }
        //获取文件保存路径
        String path = ImageUtils.getImageUniquePath(file.getOriginalFilename());
        //通过文件保存路径，将文件进行保存
        userService.loadImage(file, path);
        //返回文件名（包装成统一对象）
        return CommonResult.success(path);
    }

    @RequestMapping("register")
    public CommonResult register(@RequestBody UserInfo userInfo) {
        System.out.println(userInfo);
        // 1. 校验参数
        if(!APPUtils.hasLength(userInfo.getName(), userInfo.getPassword())) {
            return CommonResult.fail(-1, "非法参数");
        }
        // 2. 生成一个用户名
        String username = UserUtils.getUsername();
        userInfo.setUsername(username);
        // 3. 加密
        userInfo.setPassword(UserUtils.encrypt(userInfo.getPassword()));
        // 4. 请求service的添加数据库操作
        int rows = userService.register(userInfo);
        // 5. 执行结果返回
        Map<String, Object> map = new HashMap<>();
        map.put("rows", rows);
        map.put("username", username);
        return CommonResult.success(map);
    }

    @RequestMapping("/get_photo")
    public CommonResult getPhoto(@RequestBody UserInfo user) {
        String username = user.getUsername();
        UserInfo userInfo = userService.getUserByUsername(username);
        return userInfo != null ? CommonResult.success(userInfo.getPhoto()) : CommonResult.fail(-1, "没有此用户");
    }

    @RequestMapping("/login")
    public CommonResult login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        //1. 参数校验
        if(!APPUtils.hasLength(userInfo.getUsername(), userInfo.getPassword())) {
            return CommonResult.fail(-1, "非法参数！");
        }
        //2. 根据用户名查询对象
        UserInfo user = userService.getUserByUsername(userInfo.getUsername());
        if(user == null || user.getId() == 0) {
            return CommonResult.fail(-2, "用户名或者密码错误！");
        }
        //3. 验证密码（左边待测，右边数据库查出来的）
        if(!UserUtils.confirm(userInfo.getPassword(), user.getPassword())) {
            return CommonResult.fail(-2, "用户名或者密码错误！");
        }
        //4. 比较成功，将对象存储到session中
        SessionUtils.setUser(request, user);
        //5. 返回结果
        return CommonResult.success("登录成功");
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置为null也可以，但这是因为我们的判断原理的原因
        //SessionUtils.setUser(request, null);
        // 调用工具类里的注销方法
        SessionUtils.remove(request);
        response.sendRedirect("/blog_login.html");
    }

    @RequestMapping("/is_login")
    public CommonResult isLogin(HttpServletRequest request) {
        boolean login = SessionUtils.getUser(request) != null;
        return CommonResult.success(login);
    }
}
